package com.example.distributelock.controller;

import com.example.distributelock.dao.DistributeLockMapper;
import com.example.distributelock.model.DistributeLock;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@RestController
@Slf4j
public class DemoController {

    private Lock lock = new ReentrantLock();

    /**
     * 单体应用锁测试
     * @return
     * @throws Exception
     */
    @RequestMapping("singleLock")
    public String singleLock()  {
        log.info("我进入了方法");
        lock.lock();
        log.info("我进入了锁！");
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        lock.unlock();
        return "我已经执行完成！";
    }

    @Resource
    private DistributeLockMapper distributeLockMapper;

    /**
     * 使用基于数据库悲观锁的分布式锁
     */
    @RequestMapping("singleLock1")
    @Transactional(rollbackFor = Exception.class)
    public String singleLock1()  throws Exception{
        log.info("我进入了方法");
        // 若是没有使用事务，那么检索完后，事务提交，锁也就释放了，所以需要使用到事务
        DistributeLock lock = distributeLockMapper.selectDistributeLock("demo");
        if(lock == null){
            throw new Exception("分布式锁找不到");
        }
        log.info("我进入了锁！");
        try {
            Thread.sleep(20000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "我已经执行完成！";
    }


}
